import { defineStore } from 'pinia'
import { ref } from 'vue'
import { DialogQueue } from '@/utils/dialogQueue'

export const useTaskDetailsStore = defineStore('taskDetails', () => {
  // 状态
  const dialogQueue = new DialogQueue()
  const currentDialog = ref(null)
  const taskClassId = ref('')
  const taskConfig = ref('')
  const taskReturnValue = ref('')

  // 格式化 XML
  const formatXml = (xml) => {
    try {
      const parser = new DOMParser()
      const doc = parser.parseFromString(xml, "text/xml")
      
      if (doc.querySelector('parsererror')) {
        return xml
      }

      // 提取 XML 声明
      let declaration = ''
      if (xml.startsWith('<?xml')) {
        const endIndex = xml.indexOf('?>') + 2
        declaration = xml.substring(0, endIndex) + '\n'
      }
      
      function formatNode(node, indent) {
        const tab = '  '
        let result = ''
        
        if (node.nodeType === Node.ELEMENT_NODE) {
          result += indent + '<' + node.nodeName
          
          const attributes = Array.from(node.attributes)
          if (attributes.length > 0) {
            for (const attr of attributes) {
              result += '\n' + indent + tab + attr.name + '="' + attr.value + '"'
            }
            result += '\n' + indent
          }
          
          const childNodes = Array.from(node.childNodes)
          if (childNodes.length === 0) {
            result += '/>\n'
          } else {
            result += '>\n'
            
            for (const child of childNodes) {
              result += formatNode(child, indent + tab)
            }
            
            result += indent + '</' + node.nodeName + '>\n'
          }
        }
        else if (node.nodeType === Node.TEXT_NODE) {
          const text = node.textContent.trim()
          if (text) {
            result += indent + text + '\n'
          }
        }
        else if (node.nodeType === Node.COMMENT_NODE) {
          result += indent + '<!--' + node.textContent + '-->\n'
        }
        
        return result
      }
      
      return declaration + formatNode(doc.documentElement, '')
    } catch (e) {
      console.warn('XML格式化失败:', e)
      return xml
    }
  }

  // 更新值（带 XML 格式化）
  const updateValueWithXmlFormat = (value) => {
    if (!value) {
      return ''
    }

    // 检查是否为 XML 格式
    if (value.trim().startsWith('<?xml')) {
      try {
        // 使用 DOMParser 解析 XML
        const parser = new DOMParser()
        const xmlDoc = parser.parseFromString(value, "text/xml")
        
        // 如果解析成功且没有错误
        if (!xmlDoc.querySelector('parsererror')) {
          // 格式化 XML
          return formatXml(value)
        }
      } catch (e) {
        console.warn('XML解析失败:', e)
      }
    }
    
    // 如果不是 XML 或解析失败，保持原样
    return value
  }

  // 显示对话框
  const show = (classId, config, returnValue) => {
    return dialogQueue.show({
      onLoaded: () => {
        currentDialog.value = {
          taskClassId: classId || '',
          taskConfig: updateValueWithXmlFormat(config),
          taskReturnValue: updateValueWithXmlFormat(returnValue)
        }
        // 更新响应式引用
        taskClassId.value = currentDialog.value.taskClassId
        taskConfig.value = currentDialog.value.taskConfig
        taskReturnValue.value = currentDialog.value.taskReturnValue
      }
    })
  }

  // 隐藏对话框
  const hide = () => {
    dialogQueue.hide()
  }

  return {
    isVisible: dialogQueue.isVisible,
    taskClassId,
    taskConfig,
    taskReturnValue,
    show,
    hide,
    getQueueLength: dialogQueue.getQueueLength.bind(dialogQueue),
    clearQueue: dialogQueue.clearQueue.bind(dialogQueue)
  }
}) 